package meijuli.com.join51.business.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.TimerService;
import meijuli.com.join51.business.activity.LoginActivity;
import meijuli.com.join51.business.service.ApiService;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.SmsCode;
import meijuli.com.join51.business.utils.StringUtil;
import com.jhx.common.utils.ToastUtil;
import retrofit2.Call;

import static android.content.ContentValues.TAG;

/**
 * 作者:Ryan
 * 描述:找回密码
 *
 * @author jack
 */
public class FindPwdFragment extends BaseFragment implements View.OnClickListener {
    private static final int TOTAL_COUNT_TIME = 120;
    EditText mMobileInputView;
    Button mGetAuthCodeBtn;
    EditText mVerifyCodeView;
    EditText mNewPwdView;
    Button mNextStepBtn;
    EditText mNewPwdViewAgain;
    Toolbar mToolbar;
    TextView mTitleTxt;
    private TimerService.TimerServiceBinder timerServiceBinder;
    private boolean isBinded = false;
    private Call<HttpResponse<SmsCode>> mCall;
    /**
     * 密码规则，必须是数字和字母组合，并且在6-16位之间
     */
    private String regex = "^[0-9A-Za-z]{6,16}$";

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            timerServiceBinder = (TimerService.TimerServiceBinder) service;
            isBinded = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            timerServiceBinder.stopTimerService();
            isBinded = false;
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_find_pwd, container, false);
        mMobileInputView = view.findViewById(R.id.mobile_input_view);
        mGetAuthCodeBtn = view.findViewById(R.id.get_auth_code_btn);
        mVerifyCodeView = view.findViewById(R.id.verify_code_view);
        mNewPwdView = view.findViewById(R.id.newPwdView);
        mNextStepBtn = view.findViewById(R.id.btn_confirm);
        mNewPwdViewAgain = view.findViewById(R.id.newPwdView_again);
        mToolbar = view.findViewById(R.id.toolbar);
        mTitleTxt = view.findViewById(R.id.toolbar_title);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Intent intent = new Intent(getActivity(), TimerService.class);
        getActivity().bindService(intent, conn, Context.BIND_AUTO_CREATE);
        initListener();
    }

    private void initListener() {
        CustomTextWatcher textWatcher = new CustomTextWatcher();
        mGetAuthCodeBtn.setOnClickListener(this);
        mNextStepBtn.setOnClickListener(this);
        mMobileInputView.addTextChangedListener(textWatcher);
        mNewPwdViewAgain.addTextChangedListener(textWatcher);
        mVerifyCodeView.addTextChangedListener(textWatcher);
        mNewPwdView.addTextChangedListener(textWatcher);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });
        mToolbar.setNavigationIcon(R.mipmap.icon_back_white);
        mTitleTxt.setText("找回密码");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (timerServiceBinder != null && timerServiceBinder.getTimerServiceState() == TimerService.START) {
            mGetAuthCodeBtn.setEnabled(false);
            mGetAuthCodeBtn.setText(timerServiceBinder.getRemainTime() + "s");
        }
    }

    @Override
    public void onDestroy() {
        try {
            getActivity().unbindService(conn);
        } catch (Exception e) {
            Log.e(TAG, "解绑服务出错……" + e.getMessage());
        }
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        String mobileNumber = mMobileInputView.getText().toString();
        String authCode = mVerifyCodeView.getText().toString();
        String pwd = mNewPwdView.getText().toString();
        switch (v.getId()) {
            case R.id.get_auth_code_btn:
                if (StringUtil.isValidatePhoneNumber(mobileNumber)) {
                    showLoadingDialog();
                    mGetAuthCodeBtn.setEnabled(false);
                    getSmsCode(mobileNumber);
                } else {
                    ToastUtil.getInstance().showToast("请输入正确的手机号码");
                }
                break;
            case R.id.btn_confirm:
                if (!StringUtil.isValidatePhoneNumber(mobileNumber)) {
                    ToastUtil.getInstance().showToast("请输入正确的手机号码");
                    return;
                } else if (!StringUtil.isValidateVerifyCode(authCode)) {
                    ToastUtil.getInstance().showToast("请输入正确的验证码");
                    return;
                }else if (TextUtils.isEmpty(pwd) || pwd.contains(" ")
                        || pwd.length() < 6 || pwd.length() > 16) {
                    ToastUtil.getInstance().showToast("密码不能包含空格，并且在6-16位字符之间");
                    return;
                }else if (!pwd.equals(mNewPwdViewAgain.getText().toString())) {
                    ToastUtil.getInstance().showToast("两次密码不相同");
                    return;
                }
                finishChange(mobileNumber, authCode, pwd);
                break;
            default:

                break;
        }
    }

    private void finishChange(String mobileNumber, String authCode, String pwd) {
        showLoadingDialog();
        mCall = ApiManager.get().getApiService(ApiService.class)
                .findPw(mobileNumber, authCode, StringUtil.encodeToSHA256(pwd));
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<SmsCode>() {

            @Override
            public void onSuccess(String url, SmsCode data) {
                dismissDialog();
                ToastUtil.getInstance().showToast(getActivity(), "修改密码成功");
                // 去登录页
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    private void getSmsCode(String mobileNumber) {
        showLoadingDialog();
        mCall = ApiManager.get().getApiService(ApiService.class)
                .getSmsCode(mobileNumber, 2);
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<SmsCode>() {

            @Override
            public void onSuccess(String url, SmsCode data) {
                dismissDialog();
                ToastUtil.getInstance().showToast(getActivity(), "验证码已发送");
                //请求完成后再去启动倒计时
                if (isBinded) {
                    showCountDownView();
                }
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
                mGetAuthCodeBtn.setEnabled(true);
            }
        });
    }

    private void showCountDownView() {
        if (timerServiceBinder.getTimerServiceState() == TimerService.STOP) {
            timerServiceBinder.resumeTimerService();
        } else {
            timerServiceBinder.startTimerService();
        }
        mGetAuthCodeBtn.setText(TOTAL_COUNT_TIME + "s");
        timerServiceBinder.setOnRemainTimeChangeListener(new TimerService.OnRemainTimeChangeListener() {
            @Override
            public void onRemainTimeChanged(final int remainTime) {
                if (getActivity() == null) {
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mGetAuthCodeBtn == null) {
                            return;
                        }
                        if (remainTime > 0) {
                            mGetAuthCodeBtn.setText(remainTime + "s");
                        } else {
                            mGetAuthCodeBtn.setText("重新获取");
                            mGetAuthCodeBtn.setEnabled(true);
                        }
                    }
                });
            }
        });
    }

    /**
     * 检测输入
     *
     * @param str 需要检测的字符串
     * @param regex 正则匹配字符串
     */
    public static Boolean checkInput(String str, String regex) {
        Pattern pat = Pattern.compile(regex);
        Matcher mat = pat.matcher(str);
        return mat.matches();
    }

    /**
     * 检查输入
     *
     * @return
     */
    public boolean checkInput() {
        return  TextUtils.isEmpty(mMobileInputView.getText().toString().trim())
                || TextUtils.isEmpty(mVerifyCodeView.getText().toString().trim())
                || TextUtils.isEmpty(mNewPwdView.getText().toString().trim())
                || TextUtils.isEmpty(mNewPwdViewAgain.getText().toString().trim());
    }

    private class CustomTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (checkInput()) {
                mNextStepBtn.setEnabled(false);
            } else {
                mNextStepBtn.setEnabled(true);
            }
        }
    }
}
